<template>
  <!-- 文章标题分页列表页面附件下载图标显示组件,最多显示5个 -->
  <ul>
    <li v-for="item in files.slice(0, 5)">
      <a
        :href="getImageFileUrlPrefix + item.id"
        v-if="item.type == 'jpg' || item.type == 'jpeg' || item.type == 'png' || item.type == 'gif'"
      >
        <download-outlined
          :title="item.name"
          style="cursor: pointer; color: rgb(33, 125, 255); font-size: medium"
        />
      </a>
      <a :href="getPdfFileUrlPrefix + item.id" v-else-if="item.type == 'pdf'">
        <download-outlined
          :title="item.name"
          style="cursor: pointer; color: rgb(33, 125, 255); font-size: medium"
        />
      </a>
      <a :href="getFileUrlPrefix + item.id" v-else>
        <download-outlined
          :title="item.name"
          style="cursor: pointer; color: rgb(33, 125, 255); font-size: medium"
        />
      </a>
    </li>
  </ul>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';

  import { useGlobSetting } from '/@/hooks/setting';
  import { FileInfo, getImageFileApi, getPdfFileApi, getFileApi } from '/@/api/platform/file';

  import { DownloadOutlined } from '@ant-design/icons-vue';

  export default defineComponent({
    name: 'CmsArticleFilesIconDown',
    props: {
      values: {
        type: String,
        required: true,
      },
    },
    components: { DownloadOutlined },

    setup(props) {
      const files = ref<FileInfo[]>([]);

      console.log('CmsArticleFilesIconDown setup props', props);
      resolveFiles(props.values);

      const { uploadUrl } = useGlobSetting();

      const getImageFileUrlPrefix = ref<string>(uploadUrl + getImageFileApi);
      const getPdfFileUrlPrefix = ref<string>(uploadUrl + getPdfFileApi);
      const getFileUrlPrefix = ref<string>(uploadUrl + getFileApi);

      function resolveFiles(data) {
        let objs = JSON.parse(data);
        if (objs != null && objs.length > 0x0) {
          objs.forEach((element) => {
            files.value.push({
              id: element.id,
              name: element.name,
              type: element.type,
            });
          });
        }
      }

      /**
       * 打开文件
       */
      function openFile(url) {
        window.open(url, '_blank');
      }

      return {
        files,
        getImageFileUrlPrefix,
        getPdfFileUrlPrefix,
        getFileUrlPrefix,
        resolveFiles,
        openFile,
      };
    },
    watch: {
      //接收props传值由于无法确定是否完成传值和接收，因此在watch中进行处理，props传值完成或变化后再对当前的数据进行更新并调用方法对页面显示进行更新
      values: function (newVal, oldVal) {
        // console.log('watch props values', newVal);
        this.resolveFiles(newVal);
      },
    },
  });
</script>
<style scoped lang="less">
  // @import './cms.less';

  ul {
    list-style: none;
  }
  ul li {
    display: block;
    float: right;
    margin-right: 1rem;
  }
</style>
